import datetime
from io import BytesIO

from flask import Blueprint, jsonify, g, make_response, session, request
from flask_restful import Api, Resource, marshal, fields, reqparse
from apps.models.heyue_model import Agreement
from apps.models.touzhu_model import Pour
from apps.models.user_model import User
from apps.utils.code_picture import get_verify_code
from apps.utils.decorator import login_required
from exts import search

hunt_bp = Blueprint('hunt', __name__, url_prefix='/hunt')

api = Api(hunt_bp)

agreement_fileds = {
    # 合约数据化
    'id': fields.Integer,  # 编号
    'title': fields.String,  # 标题头
    'content': fields.String,  # 内容
    'end_time': fields.DateTime,  # 结束时间
    'atype': fields.String,  # 合约类型
    'add_time': fields.DateTime,  # 创建的时间
    'status': fields.Integer  # 审核的状态
}
pour_fildes = {
    # 下注表数据序列化
    'user_id': fields.String,  # 下注用户的编号
    'agree_id': fields.Integer,  # 下注合约的编号
    'money': fields.String,  # 下注的金钱
    'pour_type': fields.String,  # 合约的申诉状态
    'win_and_lowdb': fields.String,  # 是输还是赢
    'add_time': fields.DateTime  # 下注的时间
}

raps2 = reqparse.RequestParser()
raps2.add_argument('new', type=str, required=True, help='传值错误')


# 按时间最新的请求数据
class IndexLeftHunt(Resource):
    # @login_required
    def get(self):
        # user = g.user
        a = raps2.parse_args()
        b = a.get('new')
        # if user:
        if b == 'new':
            time = datetime.datetime.now()
            # 限制条件 最新并且为通过审核的
            agres = Agreement.query.filter(Agreement.end_time > time, Agreement.status == 1).all()
            agre_list = []
            for agre in agres:
                agre_list.append(agre)
                print(agre_list)

            msg = marshal(agre_list, agreement_fileds)
            data = {
                'attribute': '最新',
                'status': 200,
                'mas': msg,
            }
            return jsonify(data)


api.add_resource(IndexLeftHunt, '/')

# SPORT = 1  # 体育
#     POLITICS = 2  # 政治
#     CURRENCY = 3  # 币圈
#     ELECTRONIC = 4  # 电竞
#     OTHER = 5  # 其他
raps1 = reqparse.RequestParser()
raps1.add_argument('type', type=int, required=True, help='传值错误')


class TypeAgreement(Resource):
    def get(self):
        agres_lists = []
        rage = raps1.parse_args()
        type = rage.get('type')
        if type == 1:
            agres = Agreement.query.filter(Agreement.atype == 1, Agreement.status == 1).all()
            for i in agres:
                agres_lists.append(i)
        elif type == 2:
            agres = Agreement.query.filter(Agreement.atype == 2, Agreement.status == 1).all()
            for i in agres:
                agres_lists.append(i)
        elif type == 3:
            agres = Agreement.query.filter(Agreement.atype == 3, Agreement.status == 1).all()
            for i in agres:
                agres_lists.append(i)
        elif type == 4:
            agres = Agreement.query.filter(Agreement.atype == 4, Agreement.status == 1).all()
            for i in agres:
                agres_lists.append(i)
        elif type == 5:
            agres = Agreement.query.filter(Agreement.atype == 5, Agreement.status == 1).all()
            for i in agres:
                agres_lists.append(i)
        msg = marshal(agres_lists, agreement_fileds)
        data = {
            'type': type,
            'status': 200,
            'msgs': msg
        }
        return jsonify(data)


api.add_resource(TypeAgreement, '/type')

raps3 = reqparse.RequestParser()
raps3.add_argument('hot', type=str, required=True, help='传值错误')


class AgreementHout(Resource):
    def get(self):
        agres_lists = []
        p_list = []
        rapes = raps3.parse_args()
        age = rapes.get('hot')
        time = datetime.datetime.now()
        if age == 'hot':
            agres = Agreement.query.filter(Agreement.add_time > time, Agreement.status == 1,
                                           Pour.agree_id == Agreement.id)
            p = Pour.query.filter(Pour.agree_id == Agreement.id)
            for agre in agres:
                agres_lists.append(agre)
            p_msg = marshal(p_list, pour_fildes)
            a_msg = marshal(agres_lists, agreement_fileds)
            data = {
                'status': 200,
                'msg': '最热',
                'a_msgs': a_msg,
                'p_msgs': p_list,
            }
            return jsonify(data)


api.add_resource(AgreementHout, '/hot')

user_fildes = {
    # 用户信息数据化
    'id': fields.Integer,  # 用户编号
    'username': fields.String  # 用户名
}


class UserType(Resource):
    def get(self):
        u_list = []
        a_list = []
        p_lsit = []
        users = User.query.filter(User.id == Pour.user_id).all()
        agres = Agreement.query.filter(Agreement.id == Pour.agree_id, Pour.user_id == User.id).all()
        p = Pour.query.filter(Pour.user_id == User.id, Agreement.id == Pour.agree_id).all()
        u_list.append(users)
        a_list.append(agres)
        p_lsit.append(p)
        user_msg = marshal(u_list, user_fildes)
        agre_msg = marshal(a_list, agreement_fileds)
        pour_msg = marshal(p_lsit, pour_fildes)
        data = {
            'status': 200,
            'msg': 'user用户信息，agre合约信息,pour下注信息数据如下',
            'user_msgs': user_msg,  # 用户信息
            'agre_msgs': agre_msg,  # 合约信息
            'pour_msgs': pour_msg  # 下注的信息
        }
        return jsonify(data)

    @login_required
    def post(self):
        user = g.user
        pour_list = []
        agres_list = []
        user_grent_agreement = []
        if user:
            p = Pour.query.filter(Pour.user_id == user.id).all()
            agres = Agreement.query.filter(Agreement.id == Pour.agree_id, Pour.user_id == user.id).all()
            user_ages = Agreement.query.filter(Agreement.user_id == user.id).all()
            user_grent_agreement.append(user_ages)
            agres_list.append(agres)
            pour_list.append(p)
            p_msg = marshal(pour_list, pour_fildes)
            msg_a = marshal(agres_list, agreement_fileds)
            user_agre_msg = marshal(user_grent_agreement, agreement_fileds)
            data = {
                'status': 200,
                'msg': user.username,
                'p_msgs': p_msg,  # 用户下注
                'a_msgs': msg_a,  # 用户的 合约
                'u_msgs_a': user_agre_msg,  # 用户创建的合约
            }
            return jsonify(data)


api.add_resource(UserType, '/mypour')


class CodePicture(Resource):
    def get(self):
        image, code = get_verify_code()
        # 图片以二进制形式写入
        buf = BytesIO()
        image.save(buf, 'jpeg')
        buf_str = buf.getvalue()
        # 把buf_str作为response返回前端，并设置首部字段
        response = make_response(buf_str)
        response.headers['Content-Type'] = 'image/gif'
        # 将验证码字符串储存在session中
        session['image'] = code
        data = {
            'status': 200,
            'msg': '验证码',
            'code': code
        }
        return jsonify(data)


api.add_resource(CodePicture, '/code')

go = reqparse.RequestParser()
go.add_argument('agres', type=str, required=True, help='传值错误')

go_flides = {
    'title': fields.String
}


class Reslut(Resource):
    def get(self):
        go_lists = []
        gos = go.parse_args()
        agres = gos.get('agres')
        if agres != '':
            results = Agreement.query.msearch(agres, fields=['title', 'content'], limit=20).filter(
                Agreement.status == 1).all()
            if results:
                go_lists.append(results)
                msg = marshal(go_lists, agreement_fileds)
                data = {
                    'status': 200,
                    'type': '搜索内容如下',
                    'msgs': msg
                }
                return jsonify(data)
            else:
                data = {
                    'msg': '为搜索到%s合约' % agres
                }
                return jsonify(data)
        else:
            data = {
                'status': 400,
                'msg': '您为提供任何搜索条件'
            }
            return jsonify(data)


api.add_resource(Reslut, '/seek')
